# 自定义用户认证的后端： 实现多账户类型登录
import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from users.models import User
from meiduo_mall.utils import g_constants
from . import constants


def check_verify_email_token(token):
    """反序列化token
    :param token 序列化的用户信息
    :return user None
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else:
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user


def generate_verify_email_url(user):
    """
    生成邮箱验证链接
    :param user: 当前登录用户
    :return: verify_url
    """
    serializer = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {'user_id': user.id, 'email': user.email}
    token = serializer.dumps(data).decode()
    verify_url = g_constants.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url


def get_user_by_account(account):
    """
    根据account查询用户
    :param account: 用户名或者手机号
    :return: user
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 手机号登录
            user = User.objects.get(mobile=account)
        else:
            # 用户名登录
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户认证后代你
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        if request is None:
            """
            后端用户验证
            jwt登录方式不带request
            """
            try:
                user = User.objects.get(username=username, is_staff=True)
                # user = User.objects.get(username=username)
            except Exception as e:
                user = None

            if user is not None and user.check_password(password):
                return user

        else:
            """
            重写用户认证的方法
            """
            # 使用账号查询用户
            # 根据传入的username获取user对象。username可以是手机号也可以是账号
            user = get_user_by_account(username)
            # 校验user是否存在并校验密码是否正确
        if user and user.check_password(password):
            return user
        else:
            return None
